package edu.pku.sei.modeler.handler;

import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Locator;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

public class MiddleEndpointLocator implements Locator {

	/**
	 * 
	 */
	private Point result = null;

	/**
	 * 
	 * 
	 * @param c
	 * @param p
	 */
	public MiddleEndpointLocator(Connection c, Point p) {
		conn = c;
		figureBounds = new Rectangle();
		setDistances(p);
	}

	/**
	 * 
	 * 
	 * @param p
	 */
	public void setDistances(Point p) {
		setXDistance(p.x);
		setYDistance(p.y);
	}

	/**
	 * 
	 * 
	 * @return
	 */
	private Connection getConnection() {
		return conn;
	}

	/**
	 * 
	 * 
	 * @return
	 */
	public Point getLocation() {
		Connection conn = getConnection();
		
		if (conn.getPoints().size() == 3 && isSecondPointMidPoint(conn.getPoints().getPoint(0), conn.getPoints().getPoint(1), conn.getPoints().getPoint(2))) {
			result = new Point(conn.getPoints().getPoint(1));
		} else {
			Point startPoint = Point.SINGLETON;
			Point endPoint = new Point();
			
			int startPointPosition = 0;
			int endPointPosition = 1;
			
			conn.getPoints().getPoint(startPoint, startPointPosition); // get
			// connnections
			// ends
			conn.getPoints().getPoint(endPoint, endPointPosition);
			
			int xxx = (startPoint.x + endPoint.x) / 2 + xDistance; // calculate
			// middle
			int yyy = (startPoint.y + endPoint.y) / 2 + yDistance;
			result = new Point(xxx, yyy);
		}
		

		return result;
	}

	private boolean isSecondPointMidPoint(Point point, Point point2, Point point3) {
		double length1 = Math.sqrt((Math.pow(point.x - point2.x, 2) - Math.pow(point.y - point2.y, 2)));
		double length2 = Math.sqrt((Math.pow(point3.x - point2.x, 2) - Math.pow(point3.y - point2.y, 2)));
		
		return Math.abs(length1 - length2) < 20;
	}

	/**
	 * 
	 * 
	 * @param figure
	 */
	public void relocate(IFigure figure) {
		Point location = this.getLocation();

		Dimension figureSize = figure.getPreferredSize();
		
		location.x -= figureSize.width / 2;
//		location.y = figureSize.height / 2;
//		int xxx = (startPoint.x + endPoint.x) / 2 + xDistance;
//		int yyy = (startPoint.y + endPoint.y) / 2 + yDistance;

		figureBounds.setSize(figureSize);
		figureBounds.setLocation(location);
		figure.setBounds(figureBounds);
	}

	/**
	 * 
	 * 
	 * @param distance
	 */
	public void setXDistance(int distance) {
		xDistance = distance;
	}

	/**
	 * 
	 * 
	 * @param distance
	 */
	public void setYDistance(int distance) {
		yDistance = distance;
	}

	/**
	 * 
	 */
	private Connection conn;

	/**
	 * 
	 */
	private int xDistance, yDistance;

	/**
	 * 
	 */
	private static Rectangle figureBounds;

}
